package shun.demo.nfc;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.File;

/**
 * Created by chen on 3/4/14.
 */
public class NfcActivity extends Activity {

    private NfcAdapter mNfcAdapter;
    private boolean mAndroidBeamAvailable = false;
    private Uri[] mFileUris = new Uri[1];
    private FileUriCallback mFileUriCallback;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PackageManager pm = getPackageManager();
        if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
            Toast.makeText(this, "NFC Unavailable", Toast.LENGTH_LONG).show();
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Toast.makeText(this, "SDK Unavailable", Toast.LENGTH_LONG).show();
        } else {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            mFileUriCallback = new FileUriCallback();
            mNfcAdapter.setBeamPushUrisCallback(mFileUriCallback, this);
            Toast.makeText(this, "NFC Available", Toast.LENGTH_LONG).show();
        }
    }

    private class FileUriCallback implements NfcAdapter.CreateBeamUrisCallback {

        @Override
        public Uri[] createBeamUris(NfcEvent event) {
            String transferFile = "transferimage.jpg";
            File extDir = getExternalFilesDir(null);
            File requestFile = new File(extDir, transferFile);
            requestFile.setReadable(true, false);
            // Get a URI for the File and add it to the list of URIs
            Uri fileUri = Uri.parse("http://www.baidu.com");
            Log.e("NFC", "http://www.baidu.com");
            if (fileUri != null) {
                mFileUris[0] = fileUri;
            } else {
                Log.e("My Activity", "No File URI available for file.");
            }
//            Toast.makeText(NfcActivity.this, "NFC No File URI available for file.", Toast.LENGTH_LONG).show();
            return mFileUris;
        }
    }

    private class NdefCallback implements NfcAdapter.CreateNdefMessageCallback {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            return null;
        }
    }
}